package ljt.music.utils;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.NotificationCompat;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import ljt.music.R;

/**
 * @author jiangtao
 * @date 2018/1/3
 */

public final class Download extends AsyncTask<String, Integer, String> {
  private File file;
  private Context context;
  private String fileName;
  private NotificationCompat.Builder builder;
  private NotificationManager notificationManager;

  public Download(Context context, Bitmap bitmap) {
    this.context = context;
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(context);
    builder.setTicker("下载开始了...")
        .setContentTitle("Download")
        .setLargeIcon(bitmap)
        .setSmallIcon(R.mipmap.ic_launcher);
  }

  public Download(Context context, String fileName,Bitmap bitmap) {
    this.context = context;
    this.fileName = fileName;
    notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    builder = new NotificationCompat.Builder(context);
    builder.setTicker("下载开始了...")
        .setContentTitle("Download")
        .setLargeIcon(bitmap)
        .setSmallIcon(R.mipmap.ic_launcher);
  }

  @Override
  protected String doInBackground(String... params) {
    URL url;
    HttpURLConnection conn;
    BufferedInputStream bis = null;
    FileOutputStream fos = null;

    try {
      url = new URL(params[0]);
      Log.i("TAG", url.toString());
      conn = (HttpURLConnection) url.openConnection();

      //重定向下载链接判断
      if (conn.getResponseCode() == 301 || conn.getResponseCode() == 302) {
        conn = reconnection(conn.getHeaderField("Location"));
      }

      int fileLength = conn.getContentLength();
      InputStream inputStream = conn.getInputStream();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(5000);

      bis = new BufferedInputStream(inputStream);
      Log.i("TAG", "bis:" + bis.available());

      if (fileName == null) {
        fileName = getFileName(params[0]);
      } else {
        String substring = params[0].substring(params[0].lastIndexOf("."));
        fileName = fileName + substring;
      }
      builder.setContentTitle(fileName);
      String fileDir = Environment.getExternalStorageDirectory().getPath() + "/DownloadMp3/" + fileName;
      file = new File(fileDir);
      if (!file.exists()) {
        if (!file.getParentFile().exists()) {
          if (file.getParentFile().mkdirs()) {
            file.createNewFile();
          }
        }
      }
      fos = new FileOutputStream(file);
      byte data[] = new byte[4 * 1024];
      long total = 0;
      int count;
      while ((count = bis.read(data)) != -1) {
        total += count;
        Log.i("TAG", "total:" + total);
        publishProgress((int) (total * 100 / fileLength));
        fos.write(data, 0, count);
        fos.flush();
      }
      fos.flush();
      return "下载成功";
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (fos != null) {
          fos.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (bis != null) {
          bis.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return "网络错误";
  }

  @Override
  protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    if (progress[0] == 100) {
      builder.setTicker("下载完成！");
    }
    builder.setProgress(100, progress[0], false);
    builder.setContentText("正在下载..." + progress[0] + "%");
    notificationManager.notify(1, builder.build());
  }

  @Override
  protected void onPostExecute(String s) {
    super.onPostExecute(s);
    builder.setContentText(s);
    builder.setProgress(0, 0, false);
    notificationManager.notify(1, builder.build());
    if (fileName.endsWith(".apk")) {
      openFile(file);
    }
  }

  private HttpURLConnection reconnection(String url) {
    try {
      URL httpUrl = new URL(url.replaceAll(" ", "%20"));
      HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
      return conn;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  public static String getFileName(String url) {
    String filename = "";
    boolean isOk = false;
    // 从UrlConnection中获取文件名称
    try {
      URL myURL = new URL(url);
      URLConnection conn = myURL.openConnection();
      if (conn == null) {
        return null;
      }
      Map<String, List<String>> hf = conn.getHeaderFields();
      if (hf == null) {
        return null;
      }
      Set<String> key = hf.keySet();
      if (key == null) {
        return null;
      }
      for (String stringKey : key) {
        List<String> values = hf.get(stringKey);
        for (String value : values) {
          String result;
          try {
            result = new String(value.getBytes("ISO-8859-1"), "GBK");
            int location = result.indexOf("filename");
            if (location >= 0) {
              result = result.substring(location + "filename".length());
              filename = result.substring(result.indexOf("=") + 1);
              isOk = true;
            }
          } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
          }// ISO-8859-1 UTF-8 gb2312
        }
        if (isOk) {
          break;
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    // 从路径中获取
    if (filename == null || "".equals(filename)) {
      filename = url.substring(url.lastIndexOf("/") + 1);
    }
    return filename;
  }

  private void openFile(File file) {
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    context.startActivity(intent);
  }
}
